<template>
	<view class="">
		<div class="" id="chart"
		:newest="dataList" :updata="updataList" :change:newest="renderScript.getdataList" :change:updata="renderScript.getupdataList" :localerender="localerender" :change:localerender="renderScript.getlocal" style="width:750rpx;height:620px">
		</div>
	</view>
</template>
<script>
	import WebSocketClass from '@/util/webSocket.js'
	export default {
		// props:['id'],
		data() {
			return {
				dataList:[],
				updataList:[],
				localerender:'',
				isupdata:0,
				page:1,
				id:'',
				low:0,
				high:0,
				amount:0,
				price:0,
				moredataList:[]
			}
		},
		onLoad() {
			// this.getdataList()
			
		},
		onShow() {
			this.page=1
		},
		mounted() {
			// console.log(getApp().globalData.socketObj);
			// if (getApp().globalData.socketObj) {
			// 	// 如果sockt实例未连接
			// 	if (!getApp().globalData.socketObj.isConnect) {
			// 		getApp().globalData.socketObj.initSocket()
			// 	}
			// } else {
			// 	// 如果没有sockt实例，则创建
			// 	getApp().globalData.socketObj = new WebSocketClass(
			// 		this.$ws,
			// 		6
			// 	)
			// 	getApp().globalData.socketObj.initSocket()
			// }
			// uni.$on('message', this.getMessage)
			// this.renderScript.receiveMsg(this.localerender,this.isupdata)
			// this.sendMsg()
			
			// this.getdata(0)
			let locale=uni.getStorageSync('language')
			console.log(locale)
			let localerender=''
			if(locale=='zh'){
				localerender='zh-CN'
			}else if(locale=='tw'){
				localerender='zh-HK'
			}else if(locale=='jp'){
				localerender='zh-JP'
			}else if(locale=='ko'){
				localerender='zh-KO'
			}else{
				localerender='en-US'
			}
			this.localerender=localerender
		},
		methods: {
			// 接收消息
			getMessage(res) {
				console.log(res)
				if (res.type == 6) {
					this.renderScript.receiveMsg(res.data,this.isupdata)
				}
			},
			// getApp().globalData.socketObj.sendMsg(value)
			// uni.onKeyboardHeightChange(res => {
			// 	console.log(res.height)
			// 	uni.showToast({
			// 		title: res.height
			// 	})
			// 	let _this = this
			// 	_this.keyboardMaxHeight = res.height
			// })
			sendMsg() {
				getApp().globalData.socketObj.sendMsg(1)
			},
			getid(res){
				this.id=res
				this.getdata()
			},
			getdata(isupdata){
				// let klineData=uni.getStorageSync('klineData')
				// let klinePage=uni.getStorageSync('klinePage')
				// this.dataList=klineData?klineData:[]
				// this.page=klineData?1:klinePage
				this.$fun.ajax.post('otc/kline', {
					page:this.page,
					wallet_id:this.id
				})
				.then(res => {
					if (res.code == 1) {
						let dataList = []
						this.lineData =res.data
						dataList = res.data
						dataList.map((item)=>{
							// console.log(item)
						  item.volume = Number(item.amount);
						  item.open = Number(item.open)
						  item.close = Number(item.close)
						  item.low = Number(item.low)
						  item.high = Number(item.high)
						  // item.timestamp = uni.$u.timeFormat(item.createtime, 'yyyy-mm-dd hh:MM:ss')
						  item.timestamp=Number(item.createtime)*1000
						  // item.turnover=Math.floor(Math.random() * item.high) + 1;
						})
						if(this.page>1){
							if(res.data.length>0){
								this.page+=1
								if(res.data.length>99){
									// setTimeout(()=>{
									// 	this.getdata()
									// },1000)
								}
								this.dataList = this.dataList.concat(dataList).sort((a,b)=>a.createtime-b.createtime)
								// this.moredataList = dataList.sort((a,b)=>a.createtime-b.createtime)
								// return dataList
							}
						}else{
							if(res.data.length>0){
								if(res.data.length>99){
									this.page+=1
									// setTimeout(()=>{
									// 	this.getdata()
									// },1000)
								}
								this.dataList=dataList.sort((a,b)=>a.createtime-b.createtime)
								
							}
						}
						console.log('dataList',this.dataList)
						// uni.setStorageSync('klineData',this.dataList)
						// uni.setStorageSync('klinePage',this.page)
						// this.dataList=[{close: 0.1,date: "2024-12-13",end: "0.11",high:0.3,low: 0.1,open: 0.2,start: "0.10",timestamp: new Date().getTime(),volume: Math.floor(Math.random() * 5) + 1}]
						// this.renderScript.receiveMsg(this.localerender,0)
					}
				});
				// setInterval(()=>{
				// 	this.updataList={close: Math.random(),date: "2024-12-13",end: "0.11",high: Math.random(),low: Math.random(),open: Math.random(),start: "0.10",timestamp: new Date().getTime(),volume: Math.floor(Math.random() * 5) + 1}
				// 	this.isupdata=1
				// 	this.renderScript.receiveMsg(this.localerender,this.isupdata)
				// },1000)
			},
			 customDateStringToTimestamp(str) {
			  // 将日期字符串转换为时间戳
			  const [year, month, day] = str.split(/[- :]/)?str.split(/[- :]/):str.split(/[-]/);
			  return new Date(year, month - 1, day).getTime(); // 注意月份减1
			},
			receiveRenderData(val){
				console.log(val);
				this.isupdata=0
				console.log(this.page);
				setTimeout(()=>{
					this.getdata()
				},3000)
			}
		},
	}
</script>
<script module="renderScript" lang="renderjs">
	// import { init, dispose } from "@/util/klinecharts.min.js"
	import { init, dispose, registerLocale } from "klinecharts"
	registerLocale('zh-HK', {
	  time: '時間：',
	  open: '開：',
	  high: '高：',
	  low: '低：',
	  close: '收：',
	  volume: '成交量：',
	  turnover: '成交額：',
	  change: '漲幅：'
	})
	registerLocale('zh-JP', {
	 time: '時間:',
	 open: '開:',
	 high: '高さ:',
	 low: '低：',
	 close: '収:',
	 volume: '出来高：',
	 turnover: '出来高：',
	 change: '上昇幅:'
	})
	registerLocale('zh-KO', {
	  time: '시간:',
	  open: '켜기:',
	  high: '높이:',
	  low: '낮음:',
	  close: '받기:',
	  volume: '거래량:',
	  turnover: '거래액:',
	  change: '상승폭: '
	})
	export default {
		data() {
			return {
				lineData:[],
				linepage:1,
				list:[],
				chart:'',
				localerender:'',
				isupdata:0
			}
		},
		onReady() {
			console.log('onReady')
		},
		mounted() {
			this.getkline()
			console.log('mounted')
			
		},
		onUnload() {
			this.getdispose()
		},
		methods: {
			getdispose(){
				dispose('chart')
			},
			getkline(){
				dispose('chart')
				const chart = init('chart',{
					locale: this.localerender,
					layout: [
					    {
					      type: 'candle',
					      content: ['MA',{calcParams: [5, 10, 30],id:'candle_pane' }],
					      options: { order: Number.MIN_SAFE_INTEGER,id:"chartid",axis:{inside:false,gap:{top:50,bottom:50}}}
					    },
					    { type: 'indicator', content: ['VOL'], options: { order: 10 }  },
						{ type: 'indicator', content: ['MACD'], options: { order: 10 }  },
					  ]
				})
				chart.setLocale(this.localerender)
				// chart.setStyles({
				//   candle: {
				// 	type:"area",
				//   },
				//   yAxis: {
				//       show: false,
				//   }
				// });
				chart.setMaxOffsetLeftDistance(60)
				chart.subscribeAction(
				  'onScroll',
				  (data) => {
					  // console.log(data)
					  this.getmoredataList()
				  }
				);
				chart.setPriceVolumePrecision(4,0) 
				this.chart=chart
				// fetch('https://klinecharts.com/datas/kline.json')
				//   .then(res => res.json())
				//   .then(dataList => { 
				//   console.log(dataList)
				//   this.dataList = dataList;
				//   this.chart.applyNewData(dataList);
				//   console.log('applyNewData');
				// });
			},
			getdataList(list){
				this.chart?this.chart.applyNewData(list):""
				console.log('applyNewData');
			},
			getupdataList(list){
				this.chart?this.chart.updateData(list):""
				console.log('updateData',list);
			},
			getmoredataList(list){
				this.chart.setLoadDataCallback(({
					type,
					data,
					callback
				})=>{
					console.log(data);
					type=='backward'?callback(this.$ownerInstance.callMethod('getdata')):""
				})
			},
			getlocal(val){
				console.log(val);
				this.localerender= val
				this.chart?this.chart.setLocale(this.localerender):""
			},
			// 接收逻辑层发送的数据
			receiveMsg(newValue,isupdata) {
			  console.log('变化了', newValue,isupdata)
			  this.localerender= newValue
			  this.isupdata=isupdata
			}
		}
	}
</script>

<style lang="scss">
	.ktop{
		padding: 30rpx;
		font-size: 26rpx;
		color: #5a5a5a;
	}
</style>